const { Level } = require('level')
const db = new Level('./dao/data')
let locked = new sampleLock();

const readForUpdate = async (key) => {
    await locked.status;
    locked.lock();
    let res = await db.get(key);
    return res;
}
const writeForUpdate = async (key,value) => {
    let res = await db.put(key,value);
    locked.unlock();
    return res;
}

module.exports.readForUpdate = readForUpdate;
module.exports.writeForUpdate = writeForUpdate;

function sampleLock() {
    let callback = null
    this.status = new Promise((resolve) => {resolve(true)})
    this.lock = function() {
        this.status = new Promise((resolve) => {callback = resolve})
        console.log("locked")
    }
    this.unlock = function() {
        callback(true)
    }
}
